import { createSlice } from "@reduxjs/toolkit";
import { loginApi, getUserInfoApi } from "../../apis";

const userStore = createSlice({
  name: "user",
  // 数据初始状态
  initialState: {
    token: localStorage.getItem("token") || "",
    userInfo: {},
  },
  // 同步修改方法
  reducers: {
    setToken(state, action) {
      state.token = action.payload;
      localStorage.setItem("token", action.payload);
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload;
    },
    clearUserInfo(state) {
      state.token = "";
      state.userInfo = {};
      localStorage.removeItem("token");
    },
  },
});

// 解构出同步修改方法
const { setToken, setUserInfo, clearUserInfo } = userStore.actions;
// 获取reducer函数
const userReducer = userStore.reducer;

// 异步方法 登录获取token
const login = (params) => {
  return async (dispatch) => {
    const res = await loginApi(params);
    dispatch(setToken(res?.data?.token));
  };
};
const getUserInfo = () => {
  return async (dispatch) => {
    const res = await getUserInfoApi();
    dispatch(setUserInfo(res?.data));
  };
};

export { setToken, login, getUserInfo, clearUserInfo };
export default userReducer;
